<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
      :disabled="userState"
        v-model="queryParams.userId"
        placeholder="用户编号"
        style="width: 250px;"
        class="filter-item"
        @keyup.enter.native="queryBtn"
      />

      <el-input
      :disabled="userState"
        v-model="queryParams.parkfieldName"
        placeholder="场站名称"
        style="width: 250px;margin-left:5px;"
        class="filter-item"
        @keyup.enter.native="queryBtn"
      />

      <el-input
        v-model="queryParams.lockMac"
        placeholder="设备编号"
        style="width: 250px;margin-left:5px;"
        class="filter-item"
        @keyup.enter.native="queryBtn"
      />
<br/>
      <el-date-picker
      :disabled="userState"
        v-model="queryParams.startTime"
        value-format="yyyy-MM-dd HH:mm:ss"
        style="width: 250px;margin-top: 10px;"
        type="datetime"
        placeholder="请选择开始时间"
      ></el-date-picker>

       <el-date-picker
       :disabled="userState"
        v-model="queryParams.endTime"
        value-format="yyyy-MM-dd HH:mm:ss"
        style="width:250px;margin-left:5px;"
        type="datetime"
        placeholder="请选择结束时间"
      
      ></el-date-picker>
      <!-- default-time="23:59:59" -->
      <!-- <el-select
        v-model="listQuery.phone"
        placeholder="号码"
        clearable
        style="width: 90px"
        class="filter-item"
      > -->
      <!-- <el-option
          v-for="item in importanceOptions"
          :key="item"
          :label="item"
          :value="item"
        />
      </el-select>
      <el-date
        v-model="listQuery.number"
        placeholder="数字"
        clearable
        class="filter-item"
        style="width: 130px"
      >
        <el-option
          v-for="item in calendarTypeOptions"
          :key="item.key"
          :label="item.display_name + '(' + item.key + ')'"
          :value="item.key"
        />
      </el-date> -->

      <el-button
      :disabled="userState"
        v-waves
        class="filter-item"
        type="primary"
        style="margin-left:20px;"
        icon="el-icon-search"
        @click="queryBtn"
      >
        查询
      </el-button>
      <el-button
      :disabled="userState"
        v-waves
        :loading="downloadLoading"
        class="filter-item"
        type="primary"
        icon="el-icon-download"
        @click="checkDate"
      >
        导出
      </el-button>
    <span style="float: right;
    margin-right: 20px;
    font-weight: 600;color: #494949;">当前账号：<span style="color: #ff770f;">{{title}}</span></span>
  
  </div>
 

    <el-table
      :header-cell-style="{ background: '#ffffff', color: '#000000' }"
      :key="tableKey"
      :row-class-name="tableRowClassName"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="
        width: 100%;
        font-size: 15px;
        box-shadow: 1px 1px 8px #cdcdcd;
        border: 0px;
      "
    >
      <!-- <el-table-column
        label="ID"
        prop="id"
        sortable="custom"
        align="center"
        width="80"
        :class-name="getSortClass('id')"
      >
        <template slot-scope="{ row }">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column> -->

   

      <el-table-column label="用户编号" min-width="150px">
        <template slot-scope="{ row }">
          <span>{{ row.userId }}</span>
        </template>
      </el-table-column>

      <el-table-column label="设备名称" min-width="150px">
        <template slot-scope="{ row }">
          <span>{{row.lockName}}</span>
        </template>
      </el-table-column>

      <el-table-column label="场站名称" min-width="150px">
        <template slot-scope="{ row }">
          <span>{{row.parkfieldName}}</span>
        </template>
      </el-table-column>

      <!-- <el-table-column label="设备编号" width="150px" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.lockMac }}</span>
        </template>
      </el-table-column> -->

      <el-table-column label="开始时间" width="165px" align="center">
        <template slot-scope="{ row }">
          <span>{{ sub(row.startTime) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="结束时间" width="165px" align="center">
        <template slot-scope="{ row }">
          <span>{{ sub(row.endTime) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="离开时间" width="165px" align="center">
        <template slot-scope="{ row }">
          <span>{{ sub(row.leaveTime) }}</span>
        </template>
      </el-table-column>



      <el-table-column label="充电费用" width="100px" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.consumeFee }}</span>
        </template>
      </el-table-column>

      <el-table-column label="电量" width="100px" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.currentNum }}</span>
        </template>
      </el-table-column>

      <el-table-column label="占位费" width="100px" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.occupiedFee }}</span>
        </template>
      </el-table-column>

     <el-table-column label="支付方式" width="120px" align="center">
        <template slot-scope="{ row }">
          <el-tag
            v-if="row.payWays == '0'"
            size="medium"
            type="success"
            effect="dark"
            style="font-size: 14px"
            >微信</el-tag
          >
          <el-tag
            v-else-if="row.payWays == '1'"
            size="medium"
            type="warning"
            effect="dark"
            style="font-size: 14px"
            >余额</el-tag
          >
           <el-tag
            v-else-if="row.payWays == '2'"
            size="medium"
            type="primary"
            effect="dark"
            style="font-size: 14px"
            >充值</el-tag
          >
           <el-tag
            v-else-if="row.payWays == '3'"
            size="medium"
            type="primary"
            effect="dark"
            style="font-size: 14px"
            >太湖智行</el-tag
          >
          <el-tag v-else size="medium" type="Info" style="font-size: 14px">{{
            row.lockStatus
          }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="修改时间" width="100px" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.modifyTime }}</span>
        </template>
      </el-table-column>

      <el-table-column label="修改说明" width="300px" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.notes }}</span>
        </template>
      </el-table-column>

      <el-table-column label="订单编号" min-width="150px">
        <template slot-scope="{ row }">
          <span>{{ row.orderId }}</span>
        </template>
      </el-table-column>

      <!-- <el-table-column label="车牌号码" width="100px" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.plateNum }}</span>
        </template>     
       
      </el-table-column> -->

      <!-- <el-table-column label="车辆图片" width="100px" align="center">
        <template slot-scope="{ row }">
          <el-button :disabled="userState" type="primary" size="mini" @click="handleUpdate(row)">
           
            查看
          </el-button>
        </template>
      </el-table-column> -->


      <!-- <el-table-column
        label="操作"
        align="center"
        width="100px"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{ row }">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            Edit
          </el-button>
           <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleDelete(row,$index)">
            Delete
          </el-button> 
        </template>
      </el-table-column> -->
    </el-table>

    <!-- <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNo" :limit.sync="listQuery.pageSize" @pagination="getList" /> -->

    <el-row>
      <el-col :span="24" class="page-tool">
        <el-pagination
          layout="total,sizes,prev, pager,next,jumper"
           style="margin-top: 10px;"
          :page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 30, 40]"
          @size-change="handlePageChange"
          @current-change="handleNoChange"
        ></el-pagination>
      </el-col>
    </el-row>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" center width="1590px">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="70px"
      >
       
  <el-image 
     style="width:1536px;height:864px;"
    :src="url" 
    :preview-src-list="srcList">
    <div slot="error" class="image-slot" style="text-align:center">
        暂无图片
      </div>
  </el-image>
       
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false"> 关闭 </el-button>
        <!-- <el-button
          type="primary"
          @click="dialogStatus === 'create' ? createData() : updateData()"
        >
          提交
        </el-button> -->
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table
        :data="pvData"
        border
        fit
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false"
          >Confirm</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<style>
.el-table .warning-row {
  background: #fff5ee;
}
.el-table--enable-row-hover .el-table__body tr:hover > td {
  background-color: #fdc091;
}
.el-table__body tr.current-row > td {
  background-color: #fdc091;
}
</style>

<script>
import { listLcChargerLogDetails, exportOrder } from "@/api/order";
import waves from "@/directive/waves"; // waves directive
import { parseTime } from "@/utils";
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import axios from "axios";
import { getToken } from "@/utils/auth";
import { loadorderApi,exportChargerLogApi } from "@/api/car";
import { getNickName, getTestUserName } from "../../utils/auth";

const calendarTypeOptions = [
  { key: "CN", display_name: "China" },
  { key: "US", display_name: "USA" },
  { key: "JP", display_name: "Japan" },
  { key: "EU", display_name: "Eurozone" },
];

// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name;
  return acc;
}, {});

export default {
  name: "ComplexTable",
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: "success",
        draft: "info",
        deleted: "danger",
      };
      return statusMap[status];
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type];
    },
  },
  data() {
    
    return {


      url: '',
      tableKey: 0,
      list: [],
      pageNo: 1,
      queryParams: {
        userId: "",
        name: "",
        startTime: "",
        endTime:"",
        lockMac:"",
        parkfieldName:"",
        roleCode:""
      },
      key:"",
      pageSize: 20,
      multipleSelection: [],
      total: 0,
      listLoading: true,
      listQuery: {
        pageNo: 1,
        pageSize: 20,
        name: undefined,
        phone: undefined,
        number: undefined,
        sort: "+id",
      },
      importanceOptions: [1, 2, 3],
      calendarTypeOptions,
      sortOptions: [
        { label: "ID Ascending", key: "+id" },
        { label: "ID Descending", key: "-id" },
      ],
      statusOptions: ["published", "draft", "deleted"],
      showReviewer: false,
      temp: {
        id: undefined,
        importance: 1,
        remark: "",
        timestamp: new Date(),
        title: "",
        type: "",
        status: "published",
      },
      dialogFormVisible: false,
      dialogStatus: "",
      textMap: {
        update: "查看",
        create: "查看",
      },
      dialogPvVisible: false,
      title:"",
      pvData: [],
      rules: {
        type: [
          { required: true, message: "type is required", trigger: "change" },
        ],
        timestamp: [
          {
            type: "date",
            required: true,
            message: "timestamp is required",
            trigger: "change",
          },
        ],
        title: [
          { required: true, message: "title is required", trigger: "blur" },
        ],
      },
      downloadLoading: false,
      
    };
  },

  computed: {
    userState () {
      return getNickName() === getTestUserName();
    }
  },

  created() {
    //   this.getList()
    this.getStartTime();
    this.getendTime();
  },
  mounted: function () {
    this.key = localStorage.getItem("key");
    this.title = localStorage.getItem("title");
   
    this.queryParams.roleCode = localStorage.getItem("key");
    this.$nextTick(function () {
      this.loadorder(this.pageNo, this.pageSize);
    });
    // axios.get("/lcchargerlog/listLcChargerLogDetails?pageNo=1&pageSize=20", {
    //          headers: {
    //           pacargle:getToken()
    //         }}).then((response)=>{
    //           this.loading = true;
    //           console.log(response.data);
    //           this.list = response.data.dataList;
    //           this.total = response.data.totalNum;
    //                     setTimeout(() => {
    //             _this.listLoading = false;
    //           }, 1 * 1000);
    //         })
  },
  methods: {
    // getList() {
    //   this.listLoading = true
    //   listLcChargerLogDetails(this.listQuery).then(response => {
    //     this.list = response.data.list
    //     this.total = response.data.total

    //     // Just to simulate the time of the request
    //     setTimeout(() => {
    //       this.listLoading = false
    //     }, 1.5 * 1000)
    //   })
    // },

        //  pickerOptions: {
        //     onPick() {
        //       console.log("1111111111");
        //     }
        //   },

     change(val) {
      console.log(val)
    },

    getStartTime () {
    let date = new Date()
    let y = date.getFullYear()
    let m = date.getMonth() + 1
    m = m < 10 ? '0' + m : m
    let d = '01'   
    let hh = '00'            
    let mm = '00'         
    let ss = '00'
    let time = y + '-' + m + '-' + d + ' ' + hh + ':' + mm + ':' + ss
    this.queryParams.startTime = time;

  },

    getendTime () {
    let date = new Date()
    let y = date.getFullYear()
    let d = date.getDate()
    let m = date.getMonth() + 1
    m = m < 10 ? '0' + m : m
    // switch (m) {
    // case 1:case 3: case 5: case 7: case 8: case 10: case 12:
    //     d= '31'      
    //     break;    
    // case 2:
    //    if (y % 4 == 0 && y % 100 != 0 || y % 400 == 0) {
    //             d= '29';
    //         }else{
    //             d= '28';
    //         }      
    //     break;    
    // case 4:case 6: case 9: case 11:
    //     d= '30'    
    //     break; 
    // }     
    let hh = '23'            
    let mm = '59'         
    let ss = '59'
    let time = y + '-' + m + '-' + d + ' ' + hh + ':' + mm + ':' + ss
    this.queryParams.endTime = time;
  },


    tableRowClassName({ row, rowIndex }) {
      if (rowIndex % 2 == 0) {
        return "warning-row";
      }
      return "";
    },
    sub(value) {
      if (value === null || undefined) {
        return "";
      } else {
        value = value.substring(0, 16);
        return value;
      }
    },
    //列表页码的触发事件
    handlePageChange(pageSize) {
      this.pageSize = pageSize;
      this.loadorder(this.pageNo, this.pageSize);
    },
    handleNoChange(pageNo) {
      this.pageNo = pageNo;
      this.loadorder(this.pageNo, this.pageSize);
    },
    handleTableChange(val) {
      this.multipleSelection = val;
    },
    loadorder(pageNo, pageSize) {
      let _this = this;
      _this.loading = true;
      loadorderApi({
        pageNo: pageNo,
        pageSize: pageSize,
        userId:_this.queryParams.userId,
        name: _this.queryParams.name,
        parkfieldName:_this.queryParams.parkfieldName,
        lockMac: _this.queryParams.lockMac,
        startTime: _this.queryParams.startTime,
        endTime: _this.queryParams.endTime,
        roleCode:_this.key
      }).then((response) => {
        _this.list = response.data.dataList;
        _this.total = response.data.totalNum;
        setTimeout(() => {
          _this.listLoading = false;
        }, 1 * 1000);
      });
    },

    // queryBtn() {
    //   let _this = this;
    //   _this.loading = true;
    //   this.loadorder(_this.pageNo, _this.pageSize);
    // },


    queryBtn () {
      let _this = this
      _this.loading = true
     var stime = new Date(this.queryParams.startTime).getTime();
	   var etime = new Date(this.queryParams.endTime).getTime();
	   var day = (etime - stime)/(24*60*60*1000);
    if (day <= 0) {
		alert("结束时间不能小于开始时间");
    }else if(day > 370) {
		alert("时间范围不能大于一年");
   	}else{
    _this.loadorder(_this.pageNo, _this.pageSize);
    }

     
    },



    //////////////////////////

    // handleFilter() {
    //   this.listQuery.pageNo = 1
    //   this.getList()
    // },
    // handleModifyStatus(row, status) {
    //   this.$message({
    //     message: '操作Success',
    //     type: 'success'
    //   })
    //   row.status = status
    // },
    // sortChange(data) {
    //   const { prop, order } = data
    //   if (prop === 'id') {
    //     this.sortByID(order)
    //   }
    // },
    // sortByID(order) {
    //   if (order === 'ascending') {
    //     this.listQuery.sort = '+id'
    //   } else {
    //     this.listQuery.sort = '-id'
    //   }
    //   this.handleFilter()
    // },
    resetTemp() {
      this.temp = {
        id: undefined,
        importance: 1,
        remark: "",
        timestamp: new Date(),
        title: "",
        status: "published",
        type: "",
      };
    },
    handleCreate() {
      this.resetTemp();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    createData() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          addCar(this.temp).then(() => {
       //     this.getList();
            this.dialogFormVisible = false;
            this.$notify({
              title: "Success",
              message: "Created Successfully",
              type: "success",
              duration: 2000,
            });
          });
        }
      });
    },
    handleUpdate(row) {
  
      this.url = '';
      this.temp = Object.assign({}, row); // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp);
      this.dialogStatus = "查看";
      this.dialogFormVisible = true;
     
      this.url = row.vehicleUrl;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
     
    },
    updateData() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          updateCar(this.temp).then(() => {
       //     this.getList();
            this.dialogFormVisible = false;
            this.$notify({
              title: "Success",
              message: "Update Successfully",
              type: "success",
              duration: 2000,
            });
          });
        }
      });
    },
    handleDelete(row, index) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        deleteCar({ id: row.id }).then(() => {
     //     this.getList();
          this.dialogFormVisible = false;
          this.$notify({
            title: "Success",
            message: "Delete Successfully",
            type: "success",
            duration: 2000,
          });
        });
      });
    },
    handleFetchPv(pv) {
      fetchPv(pv).then((response) => {
        this.pvData = response.data.pvData;
        this.dialogPvVisible = true;
      });
    },

    checkDate(){
// var stime = new Date(this.queryParams.startTime.replace(/-/g,'/'));
// var etime = new Date(this.queryParams.endTime.replace(/-/g,'/'));
	var stime = new Date(this.queryParams.startTime).getTime();
	var etime = new Date(this.queryParams.endTime).getTime();
	var day = (etime - stime)/(24*60*60*1000);
  if(stime=='' || etime==''){
    alert("请输入开始时间和结束时间");
  }else if (day <= 0) {
		alert("结束时间不能小于开始时间");
	}else if(day>0 && day <= 740){
		this.handleDownload();
	}else if(day>740){
    alert("开始时间与结束时间差距不得大于2年");
  }

 // this.handleDownload();

    },
    handleDownload() {
      axios({
        method: "GET",
        url: "/lcchargerlog/exportChargerLog",
        params:this.queryParams,
        headers: { pacargle: getToken() },
        responseType: "blob", //返回是个文件
      }).then((response) => {
        this.download(response); //then直接下载，方法在下边
      });
    },
    download(res) {
      let blob = new Blob([res.data], { type: "text/xls,charset=UTF-8" }); //type是文件类，详情可以参阅blob文件类型
      // 创建新的URL并指向File对象或者Blob对象的地址
      const blobURL = window.URL.createObjectURL(blob);
      // 创建a标签，用于跳转至下载链接
      const tempLink = document.createElement("a");
      tempLink.style.display = "none";
      tempLink.href = blobURL;
      tempLink.setAttribute(
        "download",
        decodeURI(
          res.headers["content-disposition"].split(";")[1].split("=")[1]
        )
      );
      // 兼容：某些浏览器不支持HTML5的download属性
      if (typeof tempLink.download === "undefined") {
        tempLink.setAttribute("target", "_blank");
      }
      // 挂载a标签
      document.body.appendChild(tempLink);
      tempLink.click();
      document.body.removeChild(tempLink);
      // 释放blob URL地址
      window.URL.revokeObjectURL(blobURL);
    },
    formatJson(filterVal) {
      return this.list.map((v) =>
        filterVal.map((j) => {
          if (j === "timestamp") {
            return parseTime(v[j]);
          } else {
            return v[j];
          }
        })
      );
    },
    getSortClass: function (key) {
      const sort = this.listQuery.sort;
      return sort === `+${key}` ? "ascending" : "descending";
    },
  },
};
</script>
